import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "../components" 1.0

Item {
    id: taskChainPage
    width: 1200
    height: 700

    property var cmd_ctrl_relocation: 2002      //重定位
    property var cmd_nav_specify_path: 3066     //指定路径导航
    property var cmd_get_map_site_information: 1301 //获取当前地图中站点信息
    property var cmd_nav_pause: 3001            //暂停导航
    property var cmd_nav_resume: 3002           //继续导航
    property var cmd_nav_cancel: 3003           //取消导航
    property var cmd_nav_fixed_path: 3051       //固定路径导航

    // 站点数据模型
    property var siteIds: []                    // 从getMapSiteInformation获取的站点ID列表
    property var sitePositions: ({})            // 站点位置映射
    property var historyTasks: []               //历史任务
    property var filteredHistoryTasks: []       // 过滤后的任务列表
    property int currentTabIndex: 0
    property bool showOnlyToday: true           // 默认只显示当天任务
    property string taskToDelete: ""            // 要删除的任务ID
    // 当前选中的起始站点
    property string selectedStart: ""
    // 当前任务路径
    property var currentPath: []                // 格式: [{source_id, id, task_id, operation, ...}, ...]
    property string navigationState: "NONE"     // 默认无导航状态
    // TaskClientNode实例
    property var taskClientNode: null
    property string robotId: ""
    // 添加控制权相关属性
    property bool hasControlAuthority: false
    property string controlOwner: ""
    property var robotCapabilities: []            // 机器人功能列表，如 ["inspection", "spraying"]
    property string selectedCapability: ""        // 选中的功能类型项
    property var lobeData: ({})                   // 存储lobe定义数据

    // 任务类型中英文映射
    property var capabilityTranslations: ({
        "inspection": "巡检",
        "harvest": "采摘",
        "weeding": "除草",
        "grafting": "嫁接",
        "transport": "运输",
        "guide": "引导",
        "spraying": "喷药"
    })

    // 添加右键菜单
    Menu {
        id: contextMenu
        property string siteId: ""

        MenuItem {
            text: "导航到此站点"

            onTriggered: {
                // 构造JSON数据
                var jsonData = JSON.stringify({
                    "id": contextMenu.siteId
                });
                console.log("JSON数据:", jsonData);

                if (hasControlAuthority) {
                        // 固定路径导航:参数1: 3051 (命令ID) 参数2: JSON数据 (包含站点ID)  参数3: 0 (socket类型导航)
                        robotController.executeGenericCommand(cmd_nav_fixed_path, jsonData, 0);         
                    } else {
                       console.log("请先强制控制权然后再执行路径导航！");
                    }
            }
        }
    }

    /**
    * 任务客户端节点
    */
    Connections {
        target: taskClientNode
        function onFeedbackReceived(task_id, progress, status,subtask){
            showWarning("任务进度: " + progress + "%");
        }

        function onResultReceived(task_id,status,message){
            showWarning("任务结果: " + message);
        }
    }

    /**
    * robot状态信息
    */
    Connections {
        target: robotController

        function onNavigationStateUpdated(newState, newTarget){
            // 更新导航状态属性
            navigationState = newState;
            /*if (newState === "SUSPENDED") {
                // 暂停导航时，显示提示信息
                toastManager.show("导航已暂停");
            } else if (newState === "CANCELED") {
                // 取消导航时，显示提示信息
                toastManager.show("导航已取消");
            } else if (newState === "COMPLETED") {
                // 导航完成时，显示提示信息
                toastManager.show("导航已完成");
            }else if (newState === "FAILED") {
                // 导航完成时，显示提示信息
                toastManager.show("导航失败");
            }else if (newState === "RUNNING") {
                // 导航完成时，显示提示信息
                toastManager.show("导航正在运行");
            }*/
        }

        // 添加控制权状态更新处理
        function onControlAuthorityUpdated(hasAuthority, owner) {
            hasControlAuthority = hasAuthority;
            controlOwner = owner;

            // 如果 owner 是当前客户端名称，则强制设置为拥有控制权
            if (owner === robotId) {
                hasControlAuthority = true;
            }
        }
    }

    Component.onCompleted: {
        // 进入界面时获取站点信息
        robotController.getMapSiteInformation(cmd_get_map_site_information);
        // 连接信号处理
        robotController.mapStationInformationUpdated.connect(handleSiteInformation);

        // 加载历史任务数据
        loadHistoryTasks();

        // 为当前机器人创建独立的TaskClientNode实例
        var namespaceName = "/" + robotId;
        taskClientNode = taskClientFactory.createTaskClient(namespaceName);
        
    }

    // 页面销毁时清理资源
    Component.onDestruction: {
        if (taskClientNode) {
            taskClientNode.cleanup();
        }
    }

    /**
     * 自定义提示信息管理器
     */
    ToastManager {
        id: toastManager
    }

    /**
     * 显示警告信息
     */
    function showWarning(message) {
        // 显示警告信息
        toastManager.show(message);
    }

    /**
     * 根据站点描述生成lobe_definition数据
     */
    function generateLobeDefinition(stations) {
        // 按照desc分组站点
        const groupedStations = {};
        
        stations.forEach(station => {
            // 只处理有desc的站点
            if (station.desc && station.desc !== "") {
                if (!groupedStations[station.desc]) {
                    groupedStations[station.desc] = [];
                }
                groupedStations[station.desc].push(station.id);
            }
        });
        
        // 生成lobe_definition数组
        const lobeDefinition = [];
        
        // 遍历每个分组
        Object.keys(groupedStations).forEach(desc => {
            const ids = groupedStations[desc];
            // 确保每组至少有两个站点才能形成一对
            if (ids.length >= 2) {
                // 将前两个站点作为start和end配对
                lobeDefinition.push({
                    "start": ids[0],
                    "end": ids[1]
                });
            }
        });
        
        return {
            "lobe_definition": lobeDefinition
        };
    }

    /**
     * 处理站点信息更新
     */
    function handleSiteInformation(stationData) {
        try {
            console.log("接收到站点数据: " + stationData);
            if (!stationData) {
                console.error("站点数据为空");
                return;
            }
            // 解析站点数据
            const data = JSON.parse(stationData);
            if (data.stations) {
                // 提取站点ID列表
                const siteIds = data.stations.map(station => station.id);
                //console.log("提取的站点ID列表: " + JSON.stringify(siteIds));

                // 处理站点信息更新
                taskChainPage.siteIds = siteIds;
                // 初始化站点位置（可以基于算法或从其他API获取）
                initializeSitePositions(siteIds);
                
                // 生成lobe_definition数据并存储到全局属性中
                taskChainPage.lobeData = generateLobeDefinition(data.stations);
                console.log("生成的lobe_data: " + JSON.stringify(taskChainPage.lobeData));
            }
        } catch (e) {
            console.error("解析站点信息失败: " + e);
        }
    }

    /**
     * 初始化站点位置
     */
    function initializeSitePositions(siteIds) {
        if (siteIds.length === 0) return;
        
        // 计算可用空间（减去左右面板的宽度）
        var availableWidth = taskChainPage.width - 200 - 300; // 左右面板宽度
        var availableHeight = taskChainPage.height - 100; // 留出一些边距和顶部提示空间
        
        // 计算网格行列数
        var cols = Math.ceil(Math.sqrt(siteIds.length));
        var rows = Math.ceil(siteIds.length / cols);
        
        // 根据可用空间调整行列数
        if (cols > 0 && rows > 0) {
            var horizontalSpacing = Math.max(100, availableWidth / cols);
            var verticalSpacing = Math.max(100, availableHeight / rows);
            
            // 确保不会超出可用空间
            horizontalSpacing = Math.min(horizontalSpacing, availableWidth / Math.max(1, cols));
            verticalSpacing = Math.min(verticalSpacing, availableHeight / Math.max(1, rows));
            
            for (var i = 0; i < siteIds.length; i++) {
                var id = siteIds[i];
                var row = Math.floor(i / cols);
                var col = i % cols;
                sitePositions[id] = {
                    x: 50 + col * horizontalSpacing,
                    y: 100 + row * verticalSpacing  // 从100开始，为顶部提示留出空间
                };
            }
        } else {
            // 处理站点较少的情况
            for (var j = 0; j < siteIds.length; j++) {
                var id2 = siteIds[j];
                sitePositions[id2] = {
                    x: 100 + (j % 4) * 200,
                    y: 150 + Math.floor(j / 4) * 150  // 从150开始，为顶部提示留出空间
                };
            }
        }
        // 触发界面更新
        sitePositionsChanged();
    }

    /**
     * 获取站点的位置信息
     */
    function areSitesConnectable(sourceId, targetId) {
        // 检查两个站点是否可以连接
        var sourceIndex = siteIds.indexOf(sourceId);
        var targetIndex = siteIds.indexOf(targetId);
        
        // 如果任一站点不存在，返回false
        if (sourceIndex === -1 || targetIndex === -1) {
            return false;
        }
        
        // 起始站点（第一个）和结束站点（最后一个）可以互相连接
        if ((sourceIndex === 0 && targetIndex === siteIds.length - 1) || 
            (sourceIndex === siteIds.length - 1 && targetIndex === 0)) {
            return true;
        }
        
        // 其他站点只能连接相邻的站点（索引相差为1）
        return Math.abs(sourceIndex - targetIndex) === 1;
    }

    /**
     * 添加一条路径段
     * @param {string} sourceId 起始站点ID
     * @param {string} targetId 结束站点ID
     */
    function addPathSegment(sourceId, targetId) {
        // 检查站点是否相同
        if (sourceId === targetId) {
            console.log("起点和终点不能相同");
            showWarning("起点和终点不能相同");
            return false;
        }
        
        // 检查站点是否可以连接
        /*if (!areSitesConnectable(sourceId, targetId)) {
            console.log("站点 " + sourceId + " 和 " + targetId + " 不能连接");
            showWarning("站点不能连接，请按顺序选择相邻站点");
            return false;
        }*/
        
        // 如果是第一个路径段，没有特殊限制
        if (currentPath.length === 0) {
            var newSegment = {
                source_id: sourceId,
                id: targetId,
                task_id: generateTaskId()
            };

            currentPath.push(newSegment);
            currentPath = currentPath; // 触发更新
            return true;
        }
        
        // 对于后续路径段，起点必须是上一段的终点
        var lastSegment = currentPath[currentPath.length - 1];
        if (sourceId !== lastSegment.id) {
            console.log("起点必须是上一段的终点");
            showWarning("起点必须是上一段的终点");
            return false;
        }
        
        // 如果满足条件，添加路径段
        var newSegment = {
            source_id: sourceId,
            id: targetId,
            task_id: generateTaskId()
        };

        currentPath.push(newSegment);
        currentPath = currentPath; // 触发更新
        return true;
    }

    function isPathContinuous() {
        // 检查路径是否连续
        if (currentPath.length <= 1) {
            return true; // 空路径或单段路径总是连续的
        }
        
        // 检查每一段的终点是否是下一段的起点
        for (var i = 0; i < currentPath.length - 1; i++) {
            var currentSegment = currentPath[i];
            var nextSegment = currentPath[i + 1];
            
            if (currentSegment.id !== nextSegment.source_id) {
                return false; // 路径不连续
            }
        }
        
        return true;
    }

    function generateTaskId() {
        return "task_" + Date.now() + "_" + Math.floor(Math.random() * 10000);
    }

    function generatePathJson() {
        var jsonData = {
            move_task_list: currentPath
        };
        return JSON.stringify(jsonData, null, 2);
    }

    /**
    * 保存任务到数据库
    */
    function saveTaskToDatabase(startLocation, endLocation) {
        if (!databaseManager || currentPath.length === 0) return "";

        // 确保任务表存在，包含新的字段
        if (!databaseManager.tableExists("task_chains")) {
            var columns = "id TEXT PRIMARY KEY, name TEXT, path_data TEXT, created_at TEXT, " +
                        "task_type TEXT, task_start_location TEXT, task_end_location TEXT";
            if (!databaseManager.createTable("task_chains", columns)) {
                showWarning("创建任务表失败: " + databaseManager.lastError());
                return "";
            }
        }

        var taskId = generateTaskId();
        var taskData = {
            id: taskId,
            name: "任务_" + new Date().toLocaleString(),
            path_data: generatePathJson(),
            created_at: new Date().toISOString(),
            task_type: selectedCapability || "navigation",
            task_start_location: startLocation || "",
            task_end_location: endLocation || ""
        };

        // 保存到数据库
        if (!databaseManager.insertOrUpdate("task_chains", taskData, "id")) {
            showWarning("保存任务失败: " + databaseManager.lastError());
            return "";
        }
        
        console.log("任务已自动保存到数据库");
        return taskId; // 返回taskId
    }
    
    /**
    * 执行路径导航（不保存任务到数据库）
    */
    function executeNavigation() {
        // 执行前检查路径连续性
        if (!isPathContinuous()) {
            showWarning("路径不连续，请检查任务路径");
            return;
        }
        
        if (currentPath.length === 0) return;
        
        // 显示站点选择对话框（不在这里保存任务）
        selectTaskSiteDialog.open();
    }

    // 监听窗口大小变化，重新布局站点
    onWidthChanged: {
        if (siteIds.length > 0) {
            initializeSitePositions(siteIds);
        }
    }
    
    onHeightChanged: {
        if (siteIds.length > 0) {
            initializeSitePositions(siteIds);
        }
    }

    /**
     * 加载历史任务列表
     */
    function loadHistoryTasks() {
        if (!databaseManager) return;
        
        // 确保任务表存在
        if (!databaseManager.tableExists("task_chains")) {
             var columns = "id TEXT PRIMARY KEY, name TEXT, path_data TEXT, created_at TEXT, " +
                        "task_type TEXT, task_start_location TEXT, task_end_location TEXT";
            if (!databaseManager.createTable("task_chains", columns)) {
                console.log("Failed to create task_chains table: " + databaseManager.lastError());
                return;
            }
        }
        
        var result;
        if (showOnlyToday) {
            // 只查询当天的任务
            var today = new Date();
            var todayStr = today.toISOString().split('T')[0]; // 获取 YYYY-MM-DD 格式
            result = databaseManager.executeQuery(
                "SELECT id, name, path_data, created_at FROM task_chains WHERE created_at LIKE ? ORDER BY created_at DESC",
                [todayStr + '%']
            );
        } else {
            // 查询所有历史任务
            result = databaseManager.executeQuery("SELECT id, name, path_data, created_at FROM task_chains ORDER BY created_at DESC");
        }
        
        if (result) {
            taskChainPage.filteredHistoryTasks = result;
        }
    }

    /**
     * 根据任务ID加载历史任务
     */
    function loadTaskFromHistory(taskId) {
        if (!databaseManager) return;
        
        // 查询指定任务
        var result = databaseManager.executeQuery("SELECT path_data FROM task_chains WHERE id = ?", [taskId]);
        if (result && result.length > 0) {
            try {
                var taskData = JSON.parse(result[0].path_data);
                if (taskData.move_task_list) {
                    // 重新生成所有任务段的task_id
                    for (var i = 0; i < taskData.move_task_list.length; i++) {
                        taskData.move_task_list[i].task_id = generateTaskId();
                    }

                    // 加载路径数据到当前任务
                    currentPath = taskData.move_task_list;
                    showWarning("已加载历史任务: " + taskId);
                }
            } catch (e) {
                showWarning("加载历史任务失败");
            }
        }
    }

    // 主布局
    RowLayout {
        anchors.fill: parent
        spacing: 10

        // 左侧面板
        Rectangle {
            Layout.preferredWidth: 200
            Layout.fillHeight: true
            color: "#f5f5f5"
            border.color: "#ddd"

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 10
                spacing: 15

                // 标题和标签页切换
                RowLayout {
                    Layout.fillWidth: true
                    
                    Text {
                        text: "任务配置"
                        font.pixelSize: 18
                        font.bold: true
                        color: taskChainPage.currentTabIndex === 0 ? "black" : "#666"
                        MouseArea {
                            anchors.fill: parent
                            onClicked: taskChainPage.currentTabIndex = 0
                        }
                    }
                    Text {
                        text: "|"
                        font.bold: true
                    }

                    Text {
                        text: "历史任务"
                        font.pixelSize: 18
                        font.bold: true
                        color: taskChainPage.currentTabIndex === 1 ? "black" : "#666"
                        MouseArea {
                            anchors.fill: parent
                            onClicked: {
                                taskChainPage.currentTabIndex = 1
                                loadHistoryTasks() // 切换到历史任务标签时刷新数据
                            }
                        }
                    }
                    
                    Item {
                        Layout.fillWidth: true
                    }
                }
                
                // 标签页内容
                Item {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    
                    // 任务配置视图
                    Item {
                        anchors.fill: parent
                        visible: taskChainPage.currentTabIndex === 0
                        
                        ColumnLayout {
                            anchors.fill: parent
                            
                            // 站点列表
                            GroupBox {
                                Layout.fillWidth: true
                                Layout.fillHeight: true
                                title: "站点列表"

                                ListView {
                                    anchors.fill: parent
                                    clip: true
                                    model: siteIds
                                    delegate: Rectangle {
                                        width: ListView.view ? ListView.view.width : 300
                                        height: 40
                                        color: selectedStart === modelData ? "#4CAF50" : 
                                            (mouseArea.containsMouse ? "#e0e0e0" : "transparent")

                                        Text {
                                            anchors.centerIn: parent
                                            text: modelData
                                        }

                                        MouseArea {
                                            id: mouseArea
                                            anchors.fill: parent
                                            hoverEnabled: true
                                            onClicked: {
                                                if (!selectedStart) {
                                                    selectedStart = modelData;
                                                } else if (selectedStart !== modelData) {
                                                    // 添加路径段
                                                    addPathSegment(selectedStart, modelData);
                                                    selectedStart = "";
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    
                    // 历史任务视图
                    Item {
                        anchors.fill: parent
                        visible: taskChainPage.currentTabIndex === 1
                        
                        ColumnLayout {
                            anchors.fill: parent
                            
                            // 历史任务列表
                            GroupBox {
                                Layout.fillWidth: true
                                Layout.fillHeight: true
                                title: "历史任务列表"

                                ColumnLayout {
                                    anchors.fill: parent
                                    
                                    CheckBox {
                                        text: "仅显示今日任务"
                                        checked: showOnlyToday
                                        onCheckedChanged: {
                                            showOnlyToday = checked;
                                            loadHistoryTasks();
                                        }
                                    }
                                    
                                    ListView {
                                        Layout.fillWidth: true
                                        Layout.fillHeight: true
                                        clip: true
                                        model: filteredHistoryTasks
                                        delegate: Rectangle {
                                            // 使用 ListView.view.width 而不是 parent.width
                                            width: ListView.view ? ListView.view.width : 300
                                            height: 60
                                            color: mouseArea.containsMouse ? "#e0e0e0" : "transparent"

                                            ColumnLayout {
                                                anchors.fill: parent
                                                anchors.margins: 5
                                                
                                                Text {
                                                    text: modelData.id    //任务ID
                                                    font.bold: true
                                                }
                                                
                                                Text {
                                                    text: "创建时间: " + modelData.created_at
                                                    font.pixelSize: 10
                                                    color: "#666"
                                                }
                                            }

                                            MouseArea {
                                                id: mouseArea
                                                anchors.fill: parent
                                                hoverEnabled: true
                                                acceptedButtons: Qt.LeftButton | Qt.RightButton

                                                onClicked: {
                                                    if (mouse.button === Qt.LeftButton) {
                                                        loadTaskFromHistory(modelData.id);
                                                    } else if (mouse.button === Qt.RightButton) {
                                                        // 右键点击显示删除菜单
                                                        historyContextMenu.taskId = modelData.id;
                                                        historyContextMenu.popup();
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    // 添加历史任务上下文菜单
                                    Menu {
                                        id: historyContextMenu
                                        property string taskId: ""

                                        MenuItem {
                                            text: "加载任务"
                                            onTriggered: {
                                                loadTaskFromHistory(historyContextMenu.taskId);
                                            }
                                        }

                                        MenuItem {
                                            text: "修改任务ID"
                                            onTriggered: {
                                                // 打开修改任务ID对话框
                                                renameTaskDialog.taskId = historyContextMenu.taskId;
                                                renameTaskDialog.open();
                                            }
                                        }

                                        MenuItem {
                                            text: "删除任务"
                                            onTriggered: {
                                                deleteTaskFromHistory(historyContextMenu.taskId);
                                            }
                                        }
                                    }
                                }
                            }

                            Button {
                                Layout.fillWidth: true
                                text: "刷新历史任务"
                                onClicked: loadHistoryTasks()
                            }
                        }
                    }
                }
            }
        }

        // 中间可视化区域
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "white"
            border.color: "#ccc"

            // 使用ScrollView包装站点可视化区域
            ScrollView {
                id: scrollView
                anchors.fill: parent
                
                // 站点可视化
                Item {
                    id: visualizationArea
                    width: Math.max(scrollView.width, 
                                   (Object.keys(sitePositions).length > 0 ? 
                                    Math.max.apply(null, Object.keys(sitePositions).map(function(key) { 
                                        return sitePositions[key].x; 
                                    })) + 100 : 0))
                    height: Math.max(scrollView.height, 
                                    (Object.keys(sitePositions).length > 0 ? 
                                     Math.max.apply(null, Object.keys(sitePositions).map(function(key) { 
                                         return sitePositions[key].y; 
                                     })) + 100 : 0))

                    // 站点可视化
                    Repeater {
                        model: siteIds
                        delegate: Item {
                            id: siteItem
                            property string siteId: modelData
                            x: sitePositions[siteId] ? sitePositions[siteId].x - width/2 : 0
                            y: sitePositions[siteId] ? sitePositions[siteId].y - height/2 : 0
                            width: 50
                            height: 50

                            Rectangle {
                                anchors.fill: parent
                                radius: 25
                                color: selectedStart === siteId ? "#4CAF50" : "#2196F3"
                                border.color: "white"
                                border.width: 2

                                Text {
                                    anchors.centerIn: parent
                                    text: siteId
                                    color: "white"
                                    font.bold: true
                                }
                            }

                    MouseArea {
                            anchors.fill: parent
                            acceptedButtons: Qt.LeftButton | Qt.RightButton

                            onClicked: {
                                if (mouse.button === Qt.RightButton) {
                                    // z右键点击站点显示菜单
                                    contextMenu.siteId = siteItem.siteId;
                                    contextMenu.popup();
                                } else if (mouse.button === Qt.LeftButton) {
                                    if (!selectedStart) {
                                        selectedStart = siteId;
                                    } else if (selectedStart !== siteId) {
                                        // 添加路径段
                                        addPathSegment(selectedStart, siteId);
                                        selectedStart = "";
                                    }
                                }
                            }
                        }
                    }
                }

                    // 路径连接线
                    Repeater {
                        model: currentPath
                        delegate: Canvas {
                            width: visualizationArea.width
                            height: visualizationArea.height

                            onPaint: {
                                var ctx = getContext("2d");
                                var startPoint = sitePositions[modelData.source_id];
                                var endPoint = sitePositions[modelData.id];

                                if (!startPoint || !endPoint) return;

                                ctx.strokeStyle = "#FF9800";
                                ctx.lineWidth = 3;
                                ctx.beginPath();
                                ctx.moveTo(startPoint.x, startPoint.y);
                                ctx.lineTo(endPoint.x, endPoint.y);
                                ctx.stroke();

                                // 绘制箭头
                                drawArrow(ctx, startPoint.x, startPoint.y, endPoint.x, endPoint.y);
                            }

                            function drawArrow(ctx, fromX, fromY, toX, toY) {
                                var headLength = 15;
                                var angle = Math.atan2(toY - fromY, toX - fromX);

                                ctx.beginPath();
                                ctx.moveTo(toX, toY);
                                ctx.lineTo(toX - headLength * Math.cos(angle - Math.PI/6), 
                                          toY - headLength * Math.sin(angle - Math.PI/6));
                                ctx.lineTo(toX - headLength * Math.cos(angle + Math.PI/6), 
                                          toY - headLength * Math.sin(angle + Math.PI/6));
                                ctx.closePath();
                                ctx.fillStyle = "#FF9800";
                                ctx.fill();
                            }
                        }
                    }
                }
            }

            // 状态提示
            Rectangle {
                anchors.top: parent.top
                anchors.horizontalCenter: parent.horizontalCenter
                anchors.margins: 10
                width: 300
                height: 40
                color: selectedStart ? "#FFF3E0" : "#E3F2FD"
                radius: 5
                border.color: selectedStart ? "#FF9800" : "#2196F3"
                z: 10  // 确保提示在最上层

                Text {
                    anchors.centerIn: parent
                    text: selectedStart ? 
                        "已选择起点: " + selectedStart + "，请选择终点" : 
                        "请选择路径起点"
                    color: selectedStart ? "#E65100" : "#0D47A1"
                }
            }
        }

        // 右侧任务配置面板
        Rectangle {
            Layout.preferredWidth: 300
            Layout.fillHeight: true
            color: "#f5f5f5"
            border.color: "#ddd"

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 10
                spacing: 15

                // 机器人任务类型选择区域
                GroupBox {
                Layout.fillWidth: true
                title: "任务类型"

                ColumnLayout {
                    anchors.fill: parent
                    spacing: 10

                    ComboBox {
                        id: capabilitySelector
                        Layout.fillWidth: true
                        Layout.preferredHeight: 40  // 设置首选高度
                        
                        // 创建带有翻译的模型
                        model: {
                            if (robotCapabilities.length > 0) {
                                return robotCapabilities.map(function(capability) {
                                    return {
                                        "value": capability,
                                        "display": taskChainPage.capabilityTranslations[capability] || capability
                                    };
                                });
                            } else {
                                return [{"value": "navigation", "display": "导航"}];
                            }
                        }
                        
                        textRole: "display"
                        valueRole: "value"
                        
                        delegate: ItemDelegate {
                            width: capabilitySelector.width
                            height: 40  // 设置下拉项高度
                            contentItem: Text {
                                text: modelData.display
                                color: capabilitySelector.highlightedIndex === index ? "white" : "black"
                                verticalAlignment: Text.AlignVCenter
                                font.pixelSize: 14
                            }
                            highlighted: capabilitySelector.highlightedIndex === index
                            background: Rectangle {
                                color: capabilitySelector.highlightedIndex === index ? "#2196F3" : "transparent"
                            }
                        }
                        
                        contentItem: Text {
                            text: capabilitySelector.currentText
                            color: "black"
                            verticalAlignment: Text.AlignVCenter
                            font.pixelSize: 14
                            elide: Text.ElideRight
                        }
                        
                        background: Rectangle {
                            color: "white"
                            border.color: "#ccc"
                            border.width: 1
                            radius: 4
                        }
                        
                        onCurrentValueChanged: {
                            selectedCapability = currentValue;
                        }
                        
                        Component.onCompleted: {
                            // 如果有可用的功能类型，默认选择第一个
                            if (robotCapabilities.length > 0) {
                                selectedCapability = robotCapabilities[0];
                            } else {
                                selectedCapability = "navigation";
                            }
                        }
                    }
                }
            }

                // 当前路径列表
                GroupBox {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    title: "当前路径"

                    ColumnLayout {
                        anchors.fill: parent
                        
                        // 当前路径列表
                        ListView {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            clip: true
                            model: currentPath
                            delegate: Rectangle {
                                width: ListView.view ? ListView.view.width : 300
                                height: 60
                                color: index % 2 === 0 ? "#f0f0f0" : "white"
                                
                                ColumnLayout {
                                    anchors.fill: parent
                                    anchors.margins: 5

                                    Text {
                                        Layout.fillWidth: true
                                        text: modelData.source_id + " → " + modelData.id
                                        font.bold: true
                                    }

                                    Text {
                                        Layout.fillWidth: true
                                        text: modelData.task_id     //任务ID
                                        font.pixelSize: 10
                                        color: "#666"
                                    }
                                }

                                // 删除按钮
                                Button {
                                    anchors.right: parent.right
                                    anchors.verticalCenter: parent.verticalCenter
                                    text: "删除"
                                    width: 60
                                    height: 30
                                    onClicked: {
                                        currentPath.splice(index, 1);
                                        currentPath = currentPath; // 触发更新
                                    }
                                }
                            }
                        }

                        // 操作按钮
                        RowLayout {
                            Layout.fillWidth: true
                            spacing: 10

                            Button {
                                Layout.fillWidth: true
                                text: "清空"
                                onClicked: currentPath = []
                            }

                            Button {
                                Layout.fillWidth: true
                                text: "快捷路径"
                                onClicked: quickPathDialog.open()
                            }
                        }
                    }
                }

                // 生成的JSON预览
                /*GroupBox {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 200
                    title: "JSON预览"

                    ScrollView {
                        anchors.fill: parent
                        TextArea {
                            text: generatePathJson()
                            font.family: "monospace"
                            wrapMode: TextArea.NoWrap
                        }
                    }
                }*/

                // 导航状态和控制区域
                GroupBox {
                    Layout.fillWidth: true
                    title: "导航状态与控制"

                    ColumnLayout {
                        anchors.fill: parent
                        spacing: 10

                        // 导航状态显示
                        Rectangle {
                            Layout.fillWidth: true
                            Layout.preferredHeight: 40
                            color: {
                                if (navigationState === "RUNNING") return "#4CAF50";  // 绿色
                                else if (navigationState === "SUSPENDED") return "#FF9800";  // 橙色
                                else if (navigationState === "CANCELED" || navigationState === "FAILED") return "#F44336";  // 红色
                                else if (navigationState === "COMPLETED") return "#2196F3";  // 蓝色
                                else return "#9E9E9E";  // 灰色（默认）
                            }
                            radius: 5

                            Text {
                                anchors.centerIn: parent
                                text: {
                                    if (navigationState === "NONE") return "无导航";
                                    else if (navigationState === "RUNNING") return "导航运行中";
                                    else if (navigationState === "SUSPENDED") return "导航已暂停";
                                    else if (navigationState === "CANCELED") return "导航已取消";
                                    else if (navigationState === "COMPLETED") return "导航已完成";
                                    else if (navigationState === "FAILED") return "导航失败";
                                    else return "未知状态: " + navigationState;
                                }
                                color: "white"
                                font.bold: true
                                font.pixelSize: 14
                            }
                        }

                        // 导航控制按钮布局
                        RowLayout {
                            Layout.fillWidth: true
                            spacing: 10

                            Button {
                                Layout.fillWidth: true
                                //text: "暂停导航"
                                icon.source: "qrc:///icons/suspend.png"
                                highlighted: true
                                enabled: navigationState === "RUNNING"
                                onClicked: {
                                    // 根据是否有控制权选择相应的暂停方法
                                    if (hasControlAuthority) {
                                        robotController.pauseNavigation(cmd_nav_pause);
                                        console.log("通过robotController暂停导航");
                                    } else {
                                        // 使用taskClientNode发送暂停命令，这里假设cmd_nav_pause是正确的命令代码
                                        if (taskClientNode) {
                                            // 这里需要根据实际实现确定参数
                                            taskClientNode.sendTask("taskId", "navigation", "pause", "start","end","lobeData", 5, "jsonData", cmd_nav_pause);
                                            console.log("通过taskClientNode暂停导航");
                                        }
                                    }
                                }
                            }

                            Button {
                                Layout.fillWidth: true
                                //text: "继续导航"
                                icon.source: "qrc:///icons/resume.png"
                                highlighted: true
                                enabled: navigationState === "SUSPENDED"
                                onClicked: {
                                    // 根据是否有控制权选择相应的继续方法
                                    if (hasControlAuthority) {
                                        robotController.resumeNavigation(cmd_nav_resume);
                                        console.log("通过robotController继续导航");
                                    } else {
                                        // 使用taskClientNode发送继续命令
                                        if (taskClientNode) {
                                            taskClientNode.sendTask("taskId", "navigation", "resume", "start","end","lobeData", 5, "jsonData", cmd_nav_resume);
                                            console.log("通过taskClientNode继续导航");
                                        }
                                    }
                                }
                            }

                            Button {
                                Layout.fillWidth: true
                                //text: "取消导航"
                                icon.source: "qrc:///icons/cancel.png"
                                highlighted: true
                                enabled: navigationState === "RUNNING" || navigationState === "SUSPENDED"
                                onClicked: {
                                    // 根据是否有控制权选择相应的取消方法
                                    if (hasControlAuthority) {
                                        robotController.cancelNavigation(cmd_nav_cancel);
                                        console.log("通过robotController取消导航");
                                    } else {
                                        // 使用taskClientNode发送取消命令
                                        if (taskClientNode) {
                                            taskClientNode.sendTask("taskId", "navigation", "cancel", "start","end","lobeData", 5, "jsonData", cmd_nav_cancel);
                                            console.log("通过taskClientNode取消导航");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // 执行按钮
                Button {
                    Layout.fillWidth: true
                    text: "任务下发并执行"
                    highlighted: true
                    enabled: currentPath.length > 0
                    onClicked: executeNavigation()
                }
            }
        }
    }

    // 信号
    signal pathCompleted(var pathData)

    /**
     * 快速生成导航路径
     */
    function generateQuickPath() {
        var startPoint = startPointCombo.currentText
        var endPoint = endPointCombo.currentText
        
        // 检查起点和终点是否相同
        if (startPoint === endPoint) {
            pathWarningText.text = "起点和终点不能相同"
            return
        }
        
        // 查找起点和终点的索引
        var startIndex = siteIds.indexOf(startPoint)
        var endIndex = siteIds.indexOf(endPoint)
        
        // 检查站点是否存在
        if (startIndex === -1 || endIndex === -1) {
            pathWarningText.text = "站点不存在"
            return
        }
        
        // 清空当前路径
        currentPath = []
        
        // 确定遍历方向
        var step = startIndex < endIndex ? 1 : -1
        
        // 生成路径
        for (var i = startIndex; i != endIndex; i += step) {
            var sourceId = siteIds[i]
            var targetId = siteIds[i + step]
            
            // 检查站点是否可以连接
            /*if (!areSitesConnectable(sourceId, targetId)) {
                pathWarningText.text = "站点 " + sourceId + " 和 " + targetId + " 无法连接"
                currentPath = [] // 清空已生成的部分路径
                return
            }*/
            
            var newSegment = {
                source_id: sourceId,
                id: targetId,
                task_id: generateTaskId()
            }
            
            currentPath.push(newSegment)
        }
        
        // 更新路径显示
        currentPath = currentPath
        quickPathDialog.close()
        pathWarningText.text = ""
        console.log("快捷路径生成完成，共 " + currentPath.length + " 段")
    }
    
    // 快捷路径生成对话框
    Dialog {
        id: quickPathDialog
        title: "快捷路径生成"
        modal: true
        standardButtons: Dialog.Ok | Dialog.Cancel
        anchors.centerIn: parent
        width: 300
        
        ColumnLayout {
            anchors.fill: parent
            spacing: 10
            
            GridLayout {
                columns: 2
                rowSpacing: 10
                columnSpacing: 10
                Layout.fillWidth: true
                
                Text { 
                    text: "起始点:"
                    color: "black"
                    horizontalAlignment: Text.AlignRight
                    Layout.minimumWidth: 60
                }
                
                ComboBox {
                    id: startPointCombo
                    Layout.fillWidth: true
                    model: siteIds
                    delegate: ItemDelegate {
                        width: startPointCombo.width
                        contentItem: Text {
                            text: modelData
                            color: startPointCombo.highlightedIndex === index ? "white" : "black"
                        }
                        highlighted: startPointCombo.highlightedIndex === index
                    }
                    
                    contentItem: Text {
                        text: startPointCombo.currentText
                        color: "black"
                        verticalAlignment: Text.AlignVCenter
                    }
                }
                
                Text { 
                    text: "结束点:"
                    color: "black"
                    horizontalAlignment: Text.AlignRight
                    Layout.minimumWidth: 60
                }
                
                ComboBox {
                    id: endPointCombo
                    Layout.fillWidth: true
                    model: siteIds
                    delegate: ItemDelegate {
                        width: endPointCombo.width
                        contentItem: Text {
                            text: modelData
                            color: endPointCombo.highlightedIndex === index ? "white" : "black"
                        }
                        highlighted: endPointCombo.highlightedIndex === index
                    }
                    
                    contentItem: Text {
                        text: endPointCombo.currentText
                        color: "black"
                        verticalAlignment: Text.AlignVCenter
                    }
                }
            }
            
            Text {
                id: pathWarningText
                color: "red"
                font.pixelSize: 12
                wrapMode: Text.Wrap
                Layout.fillWidth: true
                Layout.preferredHeight: 20
            }
        }
        
        onOpened: {
            // 设置默认选项
            if (siteIds.length > 0) {
                // 默认起始点为第一个站点
                startPointCombo.currentIndex = 0;
                // 默认结束点为最后一个站点
                endPointCombo.currentIndex = siteIds.length - 1;
            }
        }

        onAccepted: {
            generateQuickPath()
        }

        onRejected: {
            pathWarningText.text = ""
        }
    }

    //鼠标右键删除历史任务记录
    Dialog {
        id: deleteConfirmDialog
        title: "确认删除"
        modal: true
        standardButtons: Dialog.Ok | Dialog.Cancel
        anchors.centerIn: parent

        Text {
            text: "确定要删除任务 " + taskToDelete + " 吗？此操作不可撤销。"
            wrapMode: Text.Wrap
        }

        onAccepted: {
            // 执行删除操作
            if (taskToDelete && databaseManager) {
                var result = databaseManager.executeQuery("DELETE FROM task_chains WHERE id = ?", [taskToDelete]);
                if (result !== null) {
                    console.log("任务删除成功: " + taskToDelete);
                    showWarning("任务删除成功");
                    loadHistoryTasks(); // 重新加载任务列表
                } else {
                    console.log("任务删除失败: " + databaseManager.lastError());
                    showWarning("任务删除失败: " + databaseManager.lastError());
                }
            }
            taskToDelete = ""; // 清空任务ID
        }

        onRejected: {
            taskToDelete = ""; // 清空任务ID
        }
    }

    // 选择任务开始和结束站点对话框
Dialog {
    id: selectTaskSiteDialog
    title: "选择任务开始和结束位置"
    modal: true
    standardButtons: Dialog.Ok | Dialog.Cancel
    anchors.centerIn: parent
    width: 300

    // 添加taskId属性来存储任务ID
    property string taskId: ""
    property string selectedStartSite: ""
    property string selectedEndSite: ""

    // 添加用于存储路径中站点的属性
    property var pathSiteIds: []

    ColumnLayout {
        anchors.fill: parent
        spacing: 15

        GridLayout {
            columns: 2
            rowSpacing: 15
            columnSpacing: 10
            Layout.fillWidth: true

            Text {
                text: "开始位置:"
                color: "black"  // 保持黑色文字
                horizontalAlignment: Text.AlignRight
                Layout.minimumWidth: 80
            }

            ComboBox {
                id: startSiteCombo
                Layout.fillWidth: true
                model: selectTaskSiteDialog.pathSiteIds
                delegate: ItemDelegate {
                    width: startSiteCombo.width
                    contentItem: Text {
                        text: modelData
                        color: startSiteCombo.highlightedIndex === index ? "white" : "black"
                    }
                    highlighted: startSiteCombo.highlightedIndex === index
                }

                contentItem: Text {
                    text: startSiteCombo.currentText
                    color: "black"
                    verticalAlignment: Text.AlignVCenter
                }

                onCurrentTextChanged: {
                    selectTaskSiteDialog.selectedStartSite = currentText;
                }
            }

            Text {
                text: "结束位置:"
                color: "black"  // 保持黑色文字
                horizontalAlignment: Text.AlignRight
                Layout.minimumWidth: 80
            }

            ComboBox {
                id: endSiteCombo
                Layout.fillWidth: true
                model: selectTaskSiteDialog.pathSiteIds
                delegate: ItemDelegate {
                    width: endSiteCombo.width
                    contentItem: Text {
                        text: modelData
                        color: endSiteCombo.highlightedIndex === index ? "white" : "black"
                    }
                    highlighted: endSiteCombo.highlightedIndex === index
                }

                contentItem: Text {
                    text: endSiteCombo.currentText
                    color: "black"
                    verticalAlignment: Text.AlignVCenter
                }

                onCurrentTextChanged: {
                    selectTaskSiteDialog.selectedEndSite = currentText;
                }
            }
        }
    }

    onOpened: {
        // 对话框打开时重置选择
        startSiteCombo.currentIndex = -1;
        endSiteCombo.currentIndex = -1;
        selectedStartSite = "";
        selectedEndSite = "";

        // 提取当前路径中涉及的站点
        var sites = [];
        for (var i = 0; i < currentPath.length; i++) {
            var segment = currentPath[i];
            if (sites.indexOf(segment.source_id) === -1) {
                sites.push(segment.source_id);
            }
            if (sites.indexOf(segment.id) === -1) {
                sites.push(segment.id);
            }
        }
        pathSiteIds = sites;

        // 如果有站点数据，设置默认选项
        if (pathSiteIds.length > 0) {
            // 默认开始位置为第一个站点
            startSiteCombo.currentIndex = 0;
            selectTaskSiteDialog.selectedStartSite = pathSiteIds[0];

            // 默认结束位置为最后一个站点
            endSiteCombo.currentIndex = pathSiteIds.length - 1;
            selectTaskSiteDialog.selectedEndSite = pathSiteIds[pathSiteIds.length - 1];
        }
    }

    onAccepted: {
        // 用户点击确定时，使用选定的开始和结束站点发送任务
        if (taskClientNode && selectedStartSite && selectedEndSite) {
            // 生成路径JSON
            var jsonData = generatePathJson();

            // 使用选中的功能类型项作为参数，如果没有选择则默认为"navigation"
            var operationType = selectedCapability || "navigation";

            // 保存任务到数据库（包含开始和结束位置）
            var taskId = saveTaskToDatabase(selectedStartSite, selectedEndSite);

            if (taskId) {

                 // 将lobeData转换为JSON字符串
                var lobeDataString = JSON.stringify(lobeData);

                // 发送任务，将选中的开始和结束站点作为第4和第5个参数
                console.log("发送任务到Jetson控制板: " + taskId + ", " + operationType +
                        ", 开始位置: " + selectedStartSite + ", 结束位置: " + selectedEndSite + ",lobe_data: " + lobeDataString);
                taskClientNode.sendTask(
                    taskId,
                    operationType,
                    "start",
                    selectedStartSite,  // 任务开始位置
                    selectedEndSite,    // 任务结束位置
                    lobeDataString,     // 路径陇数据
                    5,
                    jsonData,
                    cmd_nav_specify_path
                );
            }
        }
    }
}

    // 添加修改任务ID名称的对话框
    Dialog {
        id: renameTaskDialog
        title: "修改任务ID"
        modal: true
        standardButtons: Dialog.Ok | Dialog.Cancel
        anchors.centerIn: parent
        width: 300

        property string taskId: ""

        ColumnLayout {
            anchors.fill: parent
            spacing: 10

            Text {
                text: "当前任务ID: " + renameTaskDialog.taskId
                color: "black"
                font.pixelSize: 12
                wrapMode: Text.Wrap
            }

            TextField {
                id: taskIdField
                Layout.fillWidth: true
                placeholderText: "请输入新的任务ID"
            }
        }

        onAccepted: {
            if (taskIdField.text.trim() !== "") {
                renameTask(renameTaskDialog.taskId, taskIdField.text.trim());
            }
        }

        onOpened: {
            taskIdField.text = renameTaskDialog.taskId || "";
            taskIdField.selectAll();
            taskIdField.forceActiveFocus();
        }
    }

   /**
    * 重命名任务（修改任务ID）
    * @param {string} taskId 当前任务ID
    * @param {string} newId 新的任务ID
    */
    function renameTask(taskId, newId) {
        if (!databaseManager || !taskId || !newId) return false;

        try {
            // 更新数据库中的任务ID
            var query = "UPDATE task_chains SET id = ? WHERE id = ?";
            var result = databaseManager.executeQuery(query, [newId, taskId]);

            if (result !== null) {
                console.log("任务ID修改成功: " + taskId + " -> " + newId);
                showWarning("任务ID修改成功");
                loadHistoryTasks(); // 重新加载任务列表以显示更新后的ID
                return true;
            } else {
                console.log("任务ID修改失败: " + databaseManager.lastError());
                showWarning("任务ID修改失败: " + databaseManager.lastError());
                return false;
            }
        } catch (e) {
            console.log("任务ID修改异常: " + e.message);
            showWarning("任务ID修改异常: " + e.message);
            return false;
        }
    }

    /**
     * 从历史记录中删除任务
     */
    function deleteTaskFromHistory(taskId) {
        if (!databaseManager) return;

        // 设置要删除的任务ID并显示确认对话框
        taskToDelete = taskId;
        deleteConfirmDialog.open();
    }
}